/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJFrame.java
 *
 * Created on 27-dic-2011, 19:36:01
 */

package GUI;

/**
 *
 * @author andresgodoysalavert
 */
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import logica.Categoria;
import logica.Cliente;
import logica.ConexionBD;
import logica.EscribeXML;
import logica.Evento;
import logica.FindDrive;
import logica.LeeXML;
import logica.ListaApuestasXML;

public class Principal extends JFrame
{
    /** Creates new form NewJFrame */

  Evento evento = new Evento();
  Categoria categoria = new Categoria();


private void borrarTabla(){
    int i = modeloTabla.getRowCount()-1; 
    while(i>=0){
        modeloTabla.removeRow(i);
        i--;
    }

}


  private void llenarTabla(String cat) throws SQLException, Throwable{

    
    modeloTabla = evento.llenarTablaTodosEventos(cat);
  }

private void llenarComboBox() throws SQLException{
 /*LLENADO DEL COMBOBOX QUE FILTRA LAS CATEGORIAS*/

       String array[] = categoria.listaNombresCategorias();
       int i = 0;
       while (i<array.length){
        this.comboboxcategorias.addItem(array[i]);
        i++;
    }
}

public class PasswordBox {
    public String prompt() {
        JPasswordField pass = new JPasswordField(10);
        int action = JOptionPane.showConfirmDialog(null, pass,"Introduzca su Clave",JOptionPane.WARNING_MESSAGE,JOptionPane.OK_CANCEL_OPTION);
        return new String(pass.getPassword());
    }
}
  
  public Principal( String title ) throws SQLException{
      super(title);
      modeloTabla = new DefaultTableModel();
        try {
            this.llenarTabla("");
        } catch (Throwable ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
      
      initComponents();
      this.llenarComboBox();
      this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      int x = (int) screenSize.width;
      int y = (int) screenSize.height;
      setBounds(0,0,screenSize.width, (int) (screenSize.height * 0.95));
      this.jPanel1.setLayout(null);
      this.jLayeredPane1.setBounds(0,0,screenSize.width, screenSize.height);
      this.jPanel1.setBounds(0,0,screenSize.width, screenSize.height);
      this.jScrollPane1.setBounds(120, 100, screenSize.width/2, screenSize.height/2+100);
      this.comboboxcategorias.setBounds(120,screenSize.height-240,488,50);
      this.jButton1.setBounds(130+this.comboboxcategorias.getWidth(),screenSize.height-240,225,50);
      this.jLabel2.setBounds(0,0,screenSize.width, screenSize.height-100);
      this.jTable1.getTableHeader().setPreferredSize(new Dimension(this.jScrollPane1.getWidth(), 30));
      this.jTable1.setFont(new java.awt.Font("Lucida Grande", 0, 15));
      this.jTable1.getTableHeader().setFont(new java.awt.Font("Lucida Grande", 1, 15));
      this.jTable1.getTableHeader().setResizingAllowed(false);
      this.jLabel3.setBounds(960,100,400,100);
      this.jScrollPane2.setBounds(960,300,300,300);
      this.jLabel4.setBounds(960, 220, 300, 50);
      this.jButton2.setBounds(1010,screenSize.height-240, 225, 50);
      this.jLabel5.setBounds(960, 220+this.jLabel4.getHeight(), 300, 20);
      this.jTable1.removeColumn(jTable1.getColumn("Id"));
      this.jTextArea1.setLineWrap(true);
      this.jTextArea1.setWrapStyleWord(true); 
      setResizable(false);

      this.comboboxcategorias.addItem("Todos");
      this.comboboxcategorias.setVisible(true);
      this.comboboxcategorias.addItemListener(new ItemListener() {

      public void itemStateChanged(ItemEvent ie) {
            if (ie.getStateChange() == 1){
                    
                        borrarTabla();
                        jTextArea1.setText("");
                        jLabel5.setText("");
                        modeloTabla = new DefaultTableModel();
                        try {
                            llenarTabla(comboboxcategorias.getSelectedItem().toString());
                        } catch (Throwable ex) {
                            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        jTable1.setModel(modeloTabla);
                        jTable1.removeColumn(jTable1.getColumn("Id"));
                      
            }
      }
        });
  }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable(){
            public boolean isCellEditable(int rowIndex, int colIndex){
                return false;
            }
        };
        comboboxcategorias = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(153, 153, 153));
        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jScrollPane1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTable1.setBackground(new java.awt.Color(204, 204, 204));
        jTable1.setModel(modeloTabla);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        comboboxcategorias.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        comboboxcategorias.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                comboboxcategoriasMouseClicked(evt);
            }
        });
        comboboxcategorias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboboxcategoriasActionPerformed(evt);
            }
        });

        jButton1.setFont(new java.awt.Font("Lucida Grande", 0, 18));
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/images/coins.png"))); // NOI18N
        jButton1.setText(" Apostar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/images/marco3.png"))); // NOI18N

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/images/farana small 3.png"))); // NOI18N

        jScrollPane2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTextArea1.setBackground(new java.awt.Color(204, 204, 204));
        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setFont(new java.awt.Font("Lucida Grande", 2, 18));
        jTextArea1.setRows(5);
        jScrollPane2.setViewportView(jTextArea1);

        jLabel4.setFont(new java.awt.Font("Lucida Grande", 1, 18));
        jLabel4.setText("Descripcion:");

        jLabel5.setFont(new java.awt.Font("Lucida Grande", 2, 18));

        jButton2.setFont(new java.awt.Font("Lucida Grande", 0, 18)); // NOI18N
        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/images/Descargar_ICONO.png"))); // NOI18N
        jButton2.setText("Utilidad de XML");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(comboboxcategorias, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 2125, Short.MAX_VALUE))
                        .addContainerGap())
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .add(319, 319, 319)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 1720, Short.MAX_VALUE)
                                .add(jLabel1)
                                .add(106, 106, 106))
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 319, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap())))))
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(110, 110, 110)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel4)
                            .add(jPanel1Layout.createSequentialGroup()
                                .add(24, 24, 24)
                                .add(jLabel5)))
                        .add(127, 127, 127))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jButton2)
                        .add(116, 116, 116)))
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel3)
                    .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel2)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel2)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(55, 55, 55)
                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(18, 18, 18)
                        .add(jLabel3))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(92, 92, 92)
                        .add(jLabel4)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabel5)
                        .add(77, 77, 77)
                        .add(jButton2)))
                .add(4, 4, 4)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(comboboxcategorias, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 36, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1.setBounds(0, 0, 1040, 640);
        jLayeredPane1.add(jPanel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jLayeredPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1095, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jLayeredPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 746, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        int n = 3;
        if (jLabel5.getText().isEmpty()){
                JOptionPane.showMessageDialog(null,
                "No ha seleccionado ningun evento!",
                "Confirmacion",
                JOptionPane.WARNING_MESSAGE);
        }else{
        n = JOptionPane.showConfirmDialog(
                null,
                "Esta seguro que desea apostar por: "+ jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString(),
                "Confirmacion",
                JOptionPane.YES_NO_OPTION);
        }
        if(n==0){
            try {
                System.out.println("ID DE VERGA:"+Integer.parseInt(modeloTabla.getValueAt(jTable1.getSelectedRow(), 0).toString()));
                int part = evento.getCantidadParticipantes(Integer.parseInt(modeloTabla.getValueAt(jTable1.getSelectedRow(), 0).toString()));
                if (part == 2){
                    ApuestaVS apuestavs = new ApuestaVS(Integer.parseInt(modeloTabla.getValueAt(jTable1.getSelectedRow(), 0).toString()));
                    this.setVisible(false);
                    apuestavs.setVisible(true);
                }else{
                    ApuestaVarios apuestavarios = new ApuestaVarios(Integer.parseInt(modeloTabla.getValueAt(jTable1.getSelectedRow(), 0).toString()));
                    apuestavarios.setVisible(true);
                }
            } catch (SQLException ex) {
                Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }


    }//GEN-LAST:event_jButton1ActionPerformed

    private void comboboxcategoriasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboboxcategoriasActionPerformed
       //String cb=comboboxcategorias.getSelectedItem().toString();
        //modeloTabla.getDataVector().clear();
        //System.out.println(cb);
    }//GEN-LAST:event_comboboxcategoriasActionPerformed

    private void comboboxcategoriasMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_comboboxcategoriasMouseClicked
        //String cb=comboboxcategorias.getSelectedItem().toString();
        //modeloTabla.getDataVector().clear();
    }//GEN-LAST:event_comboboxcategoriasMouseClicked

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        try {
            // TODO add your handling code here:
            evento.getDescripcionEvento(Integer.parseInt(modeloTabla.getValueAt(jTable1.getSelectedRow(), 0).toString()));
            this.jTextArea1.setText(evento.getDescripcion());
            this.jLabel5.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());
        } catch (SQLException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            // TODO add your handling code here:
            String export = new PasswordBox().prompt();
            Cliente cliente = new Cliente();
            cliente.getContrasenaCliente();
            if (export.equals(cliente.getContrasena())){
               
                Object[] possibilities = {"Importar", "Exportar"};
                String s = (String)JOptionPane.showInputDialog(
                    null,
                    "Eliga una opcion:\n"
                    + "Introduzca una opcion e Introduzca un pendrive",
                    "Manejo XML",
                    JOptionPane.PLAIN_MESSAGE,
                    new javax.swing.ImageIcon(getClass().getResource("/GUI/images/Descargar_ICONO.png")),
                    possibilities,
                    "Importar");

                //If a string was returned, say so.
                if ((s != null) && (s.length() > 0)) {
                    if (s.equals("Importar")){
                        FindDrive pendrive = new FindDrive();
                        pendrive.buscarPendrive();
                        LeeXML lee=new LeeXML();
                        lee.cargarXML(pendrive.getRuta());
                        this.dispose();
                        //borrarTabla();
                        //modeloTabla = new DefaultTableModel();
                        //jTable1.setModel(modeloTabla);
                        Principal principal = new Principal("");
                        principal.setVisible(true);
                        JOptionPane.showMessageDialog(null,
                        "Archivo Importado con Exito!",
                        "Exito",
                        JOptionPane.WARNING_MESSAGE);

                    }else{
                        FindDrive pendrive = new FindDrive();
                        pendrive.buscarPendrive();
                        EscribeXML escribe = new EscribeXML();
                        ListaApuestasXML lalista_a= new ListaApuestasXML();
                        lalista_a.agregarListaApuestas();
                        escribe.EscriboListaapuesta(lalista_a,pendrive.getRuta());
                        JOptionPane.showMessageDialog(null,
                        "Archivo Exportado con Exito!",
                        "Exito",
                        JOptionPane.WARNING_MESSAGE);
                    }
                return;
                }
            }else{
                JOptionPane.showMessageDialog(null,
                "Contrasena Invalida!",
                "Exportacion",
                JOptionPane.WARNING_MESSAGE);
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
    * @param args the command line arguments
    */
  public static void main( String[] args ) throws SQLException
  {
      Principal frame = new Principal("");
      frame.setVisible(true);
  }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox comboboxcategorias;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    public javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
    public DefaultTableModel modeloTabla;
}



